#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>

#include <signal.h>
/*int main() {
    pid_t pid = fork();

    if(pid < 0) {
        perror("fork failed");
        return 1;
    }
    else if(pid == 0) {
        // 子进程
        printf("Child process, PID = %d\n", getpid());
        return 42;
    }
    else {
        // 父进程
        int status;
        pid_t terminated_pid = wait(&status);
        if(WIFEXITED(status)) {
            printf("Child process with PID %d terminated with status %d\n", terminated_pid, WEXITSTATUS(status));
        }
    }

    return 0;
}*/
/*int main() {
    pid_t pid = fork();

    if(pid < 0) {
        perror("fork failed");
        return 1;
    }
    else if(pid == 0) {
        // 子进程
        printf("Child process, PID = %d\n", getpid());
        sleep(5);
        return 42;
    }
    else {
        // 父进程
        int status;
        pid_t terminated_pid;

        // 非阻塞等待
        terminated_pid = waitpid(pid, &status, WNOHANG);
        if(terminated_pid == 0) {
            printf("Child process %d has not terminated yet.\n", pid);
        }
        else if(terminated_pid == pid) {
            if(WIFEXITED(status)) {
                printf("Child process with PID %d terminated with status %d\n", terminated_pid, WEXITSTATUS(status));
            }
        }

        // 阻塞等待
        terminated_pid = waitpid(pid, &status, 0);
        if(WIFEXITED(status)) {
            printf("Child process with PID %d terminated with status %d\n", terminated_pid, WEXITSTATUS(status));
        }
    }

    return 0;
}*/

void sigchld_handler(int signum) {
    pid_t pid;
    int status;
    while((pid = waitpid(-1, &status, WNOHANG)) > 0) {
        if(WIFEXITED(status)) {
            printf("Child process with PID %d terminated with status %d\n", pid, WEXITSTATUS(status));
        }
    }
}

int main() {
    signal(SIGCHLD, sigchld_handler);

    pid_t pid = fork();

    if(pid < 0) {
        perror("fork failed");
        return 1;
    }
    else if(pid == 0) {
        // 子进程
        printf("Child process, PID = %d\n", getpid());
        sleep(2);
        return 42;
    }
    else {
        // 父进程
        int cunt=10;
        while(cunt) {
            printf("Parent process is running.\n");
            sleep(1);
            cunt--;
        }
    }

    return 0;
}
